package org.meproj.vanet.console;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.math.BigDecimal;

import org.client.nosql.redis.RedisUtil;
import org.meproj.communication.bean.Signal;

public class FileReader {

	private File fileLocation;
	private static String TIME = "Time";
	private static int TIME_START_LOC = 16;
	
	private static String SOURCE = "Source";
	private static String PACKET = "Broadcasting a route request packet";

	private static int START_LOC = 0;
	private static int END_LOC = 0;
	
	private static enum PACKET_TYPE {
		RREQ,
		RREP,
		APPLICATION_DATA
	}
	
	public FileReader(File fileLocation) {
		// TODO Auto-generated constructor stub
		this.fileLocation = fileLocation;
	}
	
	public void readFileLine() throws IOException {
	System.out.println("Reading file: " + fileLocation);
		RandomAccessFile accessFile = new RandomAccessFile(fileLocation,"rw");
		String currLine = "";
		Signal signal = null;
		long count = 0;
		RedisUtil redisUtil = new RedisUtil();
		
		while ((currLine = accessFile.readLine()) != null ) {
			//System.out.println(currLine);
			System.out.println("FileReader.readFileLine()");
			try {
				if(currLine.contains(TIME)) {
					
						END_LOC = currLine.indexOf("sec");
						String time = currLine.substring(TIME_START_LOC, END_LOC).trim();
						signal = new Signal();
						signal.setTimeStamp(new BigDecimal(time));
					System.out.println("added time");
				} else if(currLine.contains(SOURCE)) {
					START_LOC = currLine.indexOf("Wireless Subnet_0.");
					END_LOC = currLine.indexOf(".arp");

					signal.setFromNode(currLine.substring(START_LOC, END_LOC));
					
				} else if (currLine.contains(PACKET)) {
					
					currLine = accessFile.readLine();
					
					START_LOC = currLine.indexOf("node") + 1;
					END_LOC = currLine.indexOf("(");
					
					signal.setToNode(currLine.substring(START_LOC, END_LOC));
					
					System.out.println(signal); 
					
				//	redisUtil.add(signal.getTimeStamp().toString(), signal.toString());
					count++;
				}
			} catch (Exception e) {
				//System.out.println("Current Line: " + currLine);
				//System.out.println("Start Location: " + START_LOC + "; End Location: " + END_LOC);
				e.printStackTrace();
				signal = new Signal();
			}
			
		}
		
		accessFile.close();
		System.out.println("Rows added to Redis: " + count);
	}
	
	public static void main(String[] args) {
		File file = new File("worm_console");
		FileReader fileReader = new FileReader(file);
		try {
			
			System.out.println("File path: " + file.getAbsolutePath());
			System.out.println("File Exists: " + file.exists());
			
			if(file.exists()) {
			
			   fileReader.readFileLine();
			} 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
